package com.github.jiangxch.rpc.transport.netty;

import com.github.jiangxch.rpc.transport.AbstractEndpoint;
import com.github.jiangxch.rpc.transport.ChannelHandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * @author: jiangxch
 * @date: 2021/2/20 16:53
 */
public class NettyChannelInboundHandler extends ChannelInboundHandlerAdapter {
    private ChannelHandler channelHandler;
    private AbstractEndpoint endpoint;

    public NettyChannelInboundHandler(ChannelHandler channelHandler, AbstractEndpoint endpoint) {
        this.channelHandler = channelHandler;
        this.endpoint = endpoint;
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channelHandler.onActive(NettyChannel.wrap(ctx,endpoint.getSerializer()));
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        Object deserialize = endpoint.getSerializer().deserialize(bytes);
        channelHandler.onReceive(NettyChannel.wrap(ctx,endpoint.getSerializer()), deserialize);
        super.channelRead(ctx, msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        channelHandler.caught(NettyChannel.wrap(ctx,endpoint.getSerializer()), cause);
        super.exceptionCaught(ctx, cause);
    }
}
